package com.quasar.hpatient.module.home_medicine_edit;

import android.content.Context;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.widget.ArrayAdapter;
import android.widget.Filter;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public final class FilterAdapter extends ArrayAdapter<String> {

    private CustomFilter customFilter;

    private List<String> lookList;
    private final ArrayList<String> countList = new ArrayList();

    public FilterAdapter(@NonNull Context context, int resource, @NonNull List<String> objects) {
        super(context, resource, objects);
        countList.addAll(objects);
        this.lookList = objects;
    }


    @Override
    public Filter getFilter() {
        if (null == customFilter) {
            customFilter = new CustomFilter();
        }
        return customFilter;
    }

    class CustomFilter extends Filter {

        private CustomFilter() {
        }

        @Override
        protected FilterResults performFiltering(CharSequence constraint) {
            final FilterResults result = new FilterResults();
            if (TextUtils.isEmpty(constraint)) {
                result.values = countList;
                result.count = countList.size();
                return result;
            } else {
                final ArrayList<String> tempList = new ArrayList();
                for (String str : countList) {

                    if (str.contains(constraint)) {
                        tempList.add(str);
                    }

//                    boolean ok = true;
//                    final char[] chars = str.toCharArray();
//                    for (int i = 0; i < chars.length; i++) {
//                        if (!str.contains(String.valueOf(chars[i]))) {
//                            ok = false;
//                            break;
//                        }
//                    }
//                    if (ok) {
//                        tempList.add(str);
//                    }
                }
                result.values = tempList;
                result.count = tempList.size();
                return result;
            }
        }

        @Override
        protected void publishResults(CharSequence constraint, FilterResults results) {

            lookList.clear();
            lookList.addAll((Collection<? extends String>) results.values);

            if (results.count > 0) {
                notifyDataSetChanged();
            } else {
                notifyDataSetInvalidated();
            }
        }
    }
}
